"""
Created on 2018/4/20 15:16 星期五
@author: Matt  zhuhan1401@126.com
Description: kNN进行回归分析
"""

import numpy as np
from sklearn.datasets.samples_generator import make_blobs
from sklearn.neighbors import KNeighborsRegressor
import matplotlib.pyplot as plt


nDots=40
X=5*np.random.rand(nDots,1)
Y=np.cos(X).ravel()

#添加噪声
Y+=0.2*np.random.rand(nDots)-0.1

k=5
clf=KNeighborsRegressor(k)
clf.fit(X,Y)

# 生成足够密集的点进行预测
T=np.linspace(0,5,500)[:,np.newaxis]# 增加维度 成列向量
YPred=clf.predict(T)
print(clf.score(X,Y))

# 画出拟合曲线
plt.figure(figsize=(16,10),dpi=144)
plt.scatter(X,Y,c='g',label='data',s=100)
plt.scatter(T,YPred,c='r',label='prediction',lw=4)
plt.axis('tight')
plt.title("KNeighborsRegressor (k= %i) " % k)
plt.show()

















